package cn.com.nes.site.handle.convert;

import cn.com.nes.site.entity.em.IEnum;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class EnumConvertFactory implements ConverterFactory<String, IEnum> {

    @Override
    public <T extends IEnum> Converter<String, T> getConverter(Class<T> clazz) {
        return new StringToIEnum<>(clazz);
    }

    private static class StringToIEnum<T extends IEnum> implements Converter<String, T> {

        private Class<T> targerType;

        public StringToIEnum(Class<T> targerType) {
            this.targerType = targerType;
        }

        @Override
        public T convert(String source) {
            if (StrUtil.isEmpty(source)) {
                return null;
            }

            for (T t : targerType.getEnumConstants()) {
                if (source.equals(String.valueOf(t.getKey()))) {
                    return t;
                }
            }

            return null;
        }
    }

}
